import sqlite3
from flask import g
from flask import Flask

app = Flask(__name__)


class Mydb():
    def __init__(self,dbname,tablename):
        self.db = None
        self.DATABASE = dbname
        self.tablename = tablename
        self.get_db()

    def get_db(self):
        self.db = getattr(g, '_database', None)
        if self.db is None:
            self.db = g._database = sqlite3.connect(self.DATABASE)

    @app.teardown_appcontext
    def close_connection(self, exception):
        self.db = getattr(g, '_database', None)
        if self.db is not None:
            self.db.close()

    def query_db(self,query, args=(), one=False):
        query = 'select * from {} {}'.format(self.tablename,query)
        cur = self.db.execute(query, args)
        rv = cur.fetchall()
        cur.close()
        return (rv[0] if rv else None) if one else rv

    def delete(self,query=None,isall=False):
        if isall:
            query = 'delete from {}'.format(self.tablename)
        else:
            query = 'delete from {} {}'.format(self.tablename,query)
        cur = self.db.execute(query)
        cur.close()
        self.db.commit()
        return True

    def insert(self,query):
        if self.toInsertQul(query):
            query = 'INSERT INTO {} {}'.format(self.tablename,self.toInsertQul(query))
            cur = self.db.execute(query)
            id = cur.rowcount
            cur.close()
            self.db.commit()
            return id
        else:
            return False

    def update(self,query,where):
        pass

    def toInsertQul(self,query):
        if type(query).__name__ == 'dict':
            v1=''
            k1=''
            for v,k in query.items():
                v1=v1+','+str(v)
                k1=k1+',"'+str(k)+'"'
            return '({}) VALUES ({})'.format(v1[1:],k1[1:])

        else:
            return False